<template>
  <div id="app">
    <el-container class="app-container">
      <el-aside class="app-aside" width="230px" >
        <div class="chat-list-container">
          <div class="chat-list-head">
            <div class="chat-list-head-container">
              <el-avatar class="chat-list-head-item" style="background-color: #DF016E;font-size: 20px;font-weight: bold" size="large" >
                <template>{{ userInfo.firstLetter.toUpperCase() }}</template>
              </el-avatar>
              <div class="chat-list-head-name chat-list-head-item"><strong>{{userInfo.nickName}}</strong></div>

              <el-dropdown class="chat-list-head-manageInfo" trigger="click">
                <span class="chat-list-head-icon">
                  <i style="font-size: 30px" class="el-icon-s-unfold el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="dialogFormVisible = true">账号设置</el-dropdown-item>
                  <el-dropdown-item class="change-password" command="changePassword" disabled>修改密码</el-dropdown-item>
                  <el-dropdown-item @click.native="logOut" divided>注销登录</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!--    <el-button class="chat-list-head-addBtn" round size="small" @click="friendListDrawer = true" icon="el-icon-plus">新建聊天</el-button>-->
              <!--    <el-drawer title="好友列表" :visible.sync="friendListDrawer" ></el-drawer>-->
              <EditUserInfo @changeUserInfoClose="changeUserInfoClose" :dialog-form-visible="dialogFormVisible" :user-info="userInfo"></EditUserInfo>
            </div>
          </div>
          <div class="chat-list-body">
            <div class="chat-list-body-container">
              <div class="chat-list-body-group">
                <div class="chat-list-body-group-container">
                  <div class="chat-list-body-group-head">
                    <span class="chat-list-body-group-font"><strong>群聊</strong></span>
                    <i @click="createNewChatVisible = true" style="font-size: 25px" class="el-icon-plus el-icon--right chat-list-body-group-icon"></i>
                    <CreateNewChat ref="createNewChat" @createNewChatClose="createNewChatClose" :user-info="userInfo" :create-new-chat-visible="createNewChatVisible"></CreateNewChat>
                  </div>
                  <div class="chat-list-body-group-body">
                    <div class="chat-for" v-for="(channel,index) in this.userChannelList" :key="index">
                      <router-link class="chat-for-link" v-on:click="clearNewMsg(channel.chatId)" :to="{name: 'messageDialog', params: {chatId: channel.chatId,index: index}}">
                        <div v-on:click="clearNewMsg(channel.chatId)" class="channel-name"><i class="el-icon-user" style="float: left;font-size: 18px"></i>
                          <div class="chat-name-wide">
                            {{channel.chatName}}
                          </div>
                          <el-badge v-if="findResult(channelNewMsg,channel.chatId) > 0" :value="findResult(channelNewMsg,channel.chatId)" class="item" max="99" type="danger"></el-badge>
<!--                          <div class="red-tag">-->
<!--                            <span class="badge" v-if="findResult(channelNewMsg,channel.chatId) > 0">{{findResult(channelNewMsg,channel.chatId)}}</span>-->
<!--                          </div>-->
                        </div>
                      </router-link>
                    </div>
                  </div>
                </div>
              </div>
              <div class="chat-list-body-solo">

              </div>
            </div>
          </div>
        </div>
      </el-aside>
      <el-main class="app-main" height="100%">
        <keep-alive include="ChatPage">
          <router-view :key="$route.path" @chatNameChanged="chatNameChanged" @deleteChatId="deleteChatId" @getNewMsg = 'getNewMsg' v-bind:chatIdToUpdate="chatIdToUpdate"></router-view>
        </keep-alive>
      </el-main>
    </el-container>

  </div>
</template>

<script>
import {listUserChannels} from "@/api/channel";
import {outputError} from "@/utils/exception";
import EditUserInfo from "@/components/User/EditUserInfo";
import CreateNewChat from "@/components/User/createNewChat";
import Global from "@/utils/Global";

export default {
  components: {
    EditUserInfo,
    CreateNewChat
  },
  data() {
    let currentUser = JSON.parse(sessionStorage.getItem('currentUser'))
    return {
      createNewChatVisible: false,
      dialogFormVisible: false,
      friendListDrawer: false,
      userInfo: {
        userName: currentUser.userName,
        nickName: currentUser.nickName,
        firstLetter: currentUser.firstLetter,
        avatarUrl: currentUser.avatarUrl
      },
      userChannelList: [],
      channelNewMsg: [],
      chatIdToUpdate: null,
      wsAddress: Global.WebSocketServerAddress,
    }
  },
  methods: {
    initPage(){
      let _this = this;
      if(!window.WebSocket){
        console.log('浏览器不支持websocket');
      }else{
        let serverHost = this.wsAddress;
        let userId = JSON.parse(sessionStorage.getItem('currentUser')).userName
        let url = 'wss://'+serverHost+':8081/userHome/'+userId;
        let ws = new WebSocket(url);
        ws.onopen = function (){
          console.log("客户端连接成功")
        }
        ws.onerror = function (){
          console.log("websocket连接异常")
        }
        ws.onmessage = function (e){
          let data = JSON.parse(e.data)
          if (data.messageType == 0){
            let chatInfo = data.message
            let obj = {
              chatId: chatInfo.chatId,
              newMsgNum: 0
            }
            _this.channelNewMsg.push(obj)
            _this.userChannelList.push(chatInfo)
          }
          if (data.messageType == 1){
            let userInfo = data.message
            if (userInfo.userName == _this.userInfo.userName){
              if(userInfo.nickName != null){
                _this.userInfo.nickName = userInfo.nickName
              }
              if(userInfo.avatarUrl != null){
                _this.userInfo.avatarUrl = userInfo.avatarUrl
              }
              if(userInfo.firstLetter != null){
                _this.userInfo.firstLetter = userInfo.firstLetter
              }
            }else{
              _this.createNewChatUpdate(userInfo.userName, userInfo.nickName)
            }
          }
        }
      }
    },
    createNewChatUpdate(userName, nickName){
      this.$refs.createNewChat.someoneChangeName(userName, nickName)
    },
    createNewChatClose(b){
      this.createNewChatVisible = b
    },
    changeUserInfoClose(b){
      this.dialogFormVisible = b
    },
    handleCommand(command) {
      switch(command) {
        case 'logout':
          this.logOut()
          break
        case 'editPersonalInfo':
          this.dialogFormVisible = true
          break
        case 'changePassword':
          break
      }
    },
    logOut(){
      this.$router.push('/')
    },
    chatNameChanged(chatId, chatName){
      let userChannelList = this.userChannelList
      for(let i in userChannelList){
        if (userChannelList[i].chatId == chatId){
          this.userChannelList[i].chatName = chatName
        }
      }
    },
    deleteChatId(chatId){
      let userChannelList = this.userChannelList
      for(let i in userChannelList){
        if (userChannelList[i].chatId == chatId){
          this.userChannelList.splice(i,1)
          this.$router.push('/welcome')
        }
      }
    },
    findResult(obj, chatId){
      let resultObj = null
      resultObj = obj.find(function (kkk) {
        if (kkk.chatId == chatId) {
          return kkk;
        }
      })
      return resultObj.newMsgNum
    },
    clearNewMsg(chatId){
      let obj = this.channelNewMsg
      obj.find(function (kkk) {
        if (kkk.chatId == chatId) {
          kkk.newMsgNum = 0
        }
      })
    },
    getNewMsg(chatIdToUpdate){
      if(this.$route.params.chatId == chatIdToUpdate){
        return
      }
      let obj = this.channelNewMsg
      obj.find(function (kkk) {
        if (kkk.chatId == chatIdToUpdate) {
          kkk.newMsgNum++
        }
      })
    },
  },
  mounted() {
    this.initPage();
  },
  beforeCreate() {
    let userName = JSON.parse(sessionStorage.getItem('currentUser')).userName
    listUserChannels(userName)
        .then(response => {
          let channelList = response.data.data
          let channelNewMsgTemp = []
          this.userChannelList = channelList
          for (let i in channelList){
            let obj = {
              chatId: channelList[i].chatId,
              newMsgNum: 0
            }
            channelNewMsgTemp.push(obj)
          }
          this.channelNewMsg = channelNewMsgTemp
        })
        .catch(error => {
          outputError(this, error)
        })
  },
  destroyed() {
    this.ws.onclose(undefined);
  },
}
</script>

<style>
html,body,#app {
  width: 100%;
  height: 100%;
  background-color: #F3F6F8;
  margin: 0px;
  padding: 0px;
}
.el-popover{
  height: 200px;
  width: 400px;
  overflow: auto;
}
.app-aside {
  width: 150px;
  overflow: hidden;
}
.app-main {
  /*background-color: #a4a8c7;*/
  color: #333;
  text-align: center;

  padding: 0px;
  height: 100%;
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;

  color: #2c3e50;
}
.el-container{
  padding: 0px;
  margin: 0px;
  height: 100vh;
}
.chat-list-container{
  height: 100%;
}
.chat-list-head{
  height: 10%;
}
.chat-list-body{
  height: 90%;
  background-color: #2263af;
}
.chat-list-head-container{
  height: 100%;
  background-color: #0a53a4;
}
.chat-list-head-item{
  margin-top: 15px;
  margin-left: 10px;
  float: left;
}
.chat-list-head-manageInfo{
  float: right;
  margin-right: 10px;
  margin-top: 20px;
}
.chat-list-head-name{
  color: #F3F6F8;
  margin-top: 25px;
  font-size: 20px;
}
.chat-list-head-icon:hover{
  color: #F3F6F8;
}
.chat-list-head-icon{
  cursor: pointer;
  color: lightgrey;
}
.chat-list-body-container{
  height: 100%;
}
.chat-list-body-group-container{
  background-color: #2263af;
  height: 100%;
}
.chat-list-body-group-font{
  color: #97b8dd;
  font-size: 22px;
  margin-left: 10px;
  margin-top: 3px;
  float: left;
}
.chat-list-body-group-icon{
  margin-top: 5px;
  color: #97b8dd;
  float: right;
}
.chat-list-body-group-icon:hover{
  color: #ffffff;
}
.chat-list-body-group-head{
  height: 32px;
}
.chat-Head-Icon{

}
.channel-name{
  display: inline-block;
  margin-left: 10px;
  width: 200px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: top;
  color: #fff;
}
.chat-list-body-group-body{
  margin-top: 10px;
  height: 600px;
  overflow: auto;
}
.chat-list-body-group-body::-webkit-scrollbar {
  width: 4px;
  /*height: 4px;*/
}
.chat-list-body-group-body::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
  background: rgb(222, 222, 222);
}
.chat-list-body-group-body::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
  border-radius: 0;
  background: rgba(0,0,0,0.1);
}
.chat-for{
  height: 33px;
  overflow: hidden;
}
.chat-for:hover{
  background-color: #3a8ee6;
}
.chat-name-wide{
  float: left;
  width: 80%;
  overflow: hidden;
  height: 21px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
a{
  padding-top: 8px;
  width: 100%;
  display: inline-block;
  height: 100%;
}
.el-badge__content--danger{
  background-color: red;
}
.change-password:hover{
  cursor: not-allowed;
}

</style>
